package com.example.bleuesprit.parkAndroidClient;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Surface;
import android.view.WindowManager;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.CameraPosition;

public class AMapEx {
	private Context context;
	private AMap aMap;
	private SensorManager mSensorManager;
	private Sensor mOrientationSensor;
	private float angle;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			CameraPosition position = aMap.getCameraPosition();
			aMap.moveCamera(CameraUpdateFactory
					.newCameraPosition(CameraPosition.builder().target(position.target).tilt(position.tilt).zoom(position.zoom)
							.bearing((Float) msg.obj).build()));
//			aMap.moveCamera(CameraUpdateFactory.changeBearing((Float) msg.obj));
		}
	};

	@SuppressWarnings("deprecation")
	public AMapEx(Context context, AMap aMap) {
		this.context = context;
		this.aMap = aMap;
		mSensorManager = (SensorManager) context
				.getSystemService(Context.SENSOR_SERVICE);
		mOrientationSensor = mSensorManager
				.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		angle = aMap.getCameraPosition().bearing;
	}

	public void setRotateWithSensor(boolean enabled) {
		if (mOrientationSensor == null)
			return;
		if (enabled) {
			mSensorManager.registerListener(mSensorEventListener,
					mOrientationSensor, SensorManager.SENSOR_DELAY_GAME);
		} else {
			mSensorManager.unregisterListener(mSensorEventListener);
		}
	}

	private SensorEventListener mSensorEventListener = new SensorEventListener() {
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			float orientation = event.values[0];
			WindowManager wm = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
			int rotation = wm.getDefaultDisplay().getRotation();
			//Log.d("AMapEx", "rotation: " + rotation);
			if (event.accuracy > SensorManager.SENSOR_STATUS_ACCURACY_LOW) {
				if (rotation == Surface.ROTATION_0) {
				} else if (rotation == Surface.ROTATION_90) {
					orientation = (orientation + 90) % 360;
				} else if (rotation == Surface.ROTATION_180) {
					orientation = (orientation + 180) % 360;
				} else if (rotation == Surface.ROTATION_270) {
					orientation = (orientation + 270) % 360;
				}
				if (Math.abs(angle - orientation) > 0.5) {
					angle = orientation;
					Message msg = handler.obtainMessage(1, orientation);
					msg.sendToTarget();
				}
			}
		}
	};

}
